//
//  AttachmentPhotoCell.m
//  Estate
//
//  Created by wangdongdong on 16/8/17.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "AttachmentPhotoCell.h"
#import "UICustomCollectionView.h"
#import "TweetSendImageCCell.h"
#import "UIView+Frame.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"


@interface AttachmentPhotoCell ()

@property (strong, nonatomic) UICustomCollectionView *mediaView;
@property (strong, nonatomic) NSMutableDictionary *imageViewsDict;

@end

@implementation AttachmentPhotoCell

/*
 *  解决 Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the de 警告
 */
/*
 *  以下注释代码严重bug 导致附件选满9张无法删除!
 */
//-(void)layoutSubviews {
//    [super layoutSubviews];
//    self.mediaView.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height );
//}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor whiteColor];
        
        if (!self.mediaView) {
            
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
            self.mediaView = [[UICustomCollectionView alloc] initWithFrame:CGRectMake(kPaddingLeftWidth, 0, kScreen_Width/2 - 2*kPaddingLeftWidth, 80) collectionViewLayout:layout];
            
            self.mediaView.scrollEnabled = NO;
            [self.mediaView setBackgroundView:nil];
            [self.mediaView setBackgroundColor:[UIColor clearColor]];
            [self.mediaView registerClass:[TweetSendImageCCell class] forCellWithReuseIdentifier:kCCellIdentifier_TweetSendImage];
            self.mediaView.dataSource = self;
            self.mediaView.delegate = self;
            [self.contentView addSubview:self.mediaView];
        }
        if (!_imageViewsDict) {
            _imageViewsDict = [[NSMutableDictionary alloc] init];
        }
    }
    return self;
}

- (void)setCurTweet:(Tweet *)curTweet{
    if (_curTweet != curTweet) {
        _curTweet = curTweet;
    }
    [self.mediaView setHeight:[AttachmentPhotoCell cellHeightWithObj:_curTweet]];
    
    [_mediaView reloadData];
}

+ (CGFloat)cellHeightWithObj:(id)obj {
    CGFloat cellHeight = kTitleTop + kGapV;
    if ([obj isKindOfClass:[Tweet class]]) {
        Tweet *curTweet = (Tweet *)obj;
        NSInteger row;        
        row = ceilf((float)(curTweet.tweetImages.count + 1));
        cellHeight += (([TweetSendImageCCell ccellSize].height +10) *row);
    }
    return cellHeight;
}


#pragma mark Collection M
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger num = _curTweet.selectedAssetURLs.count;
    //设置最多选择图片
    if(self.isEdit){
        return num < 9? num+ 1: num;
    }else{
        return num < 9? num: num;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger num=indexPath.row;
    
    __weak typeof(self) weakSelf = self;
    
    TweetSendImageCCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:kCCellIdentifier_TweetSendImage forIndexPath:indexPath];
    ccell.isEdit=self.isEdit;
    
    
    NSString *urlStr=@"";
    
    if (indexPath.row < _curTweet.selectedAssetURLs.count) {
        //巡检带入 整改前  不显示删除按钮
        if(self.isDEL){
            ccell.isDEL=NO;
            NSString *str=[ _curTweet.selectedAssetURLs objectAtIndex:num];
            //        //比较巡检带入的附件 和自己新增的附件的差异  巡检带入不能删除
            if([self.fileArray containsObject:str]){
                //不显示删除按钮
                NSLog(@"str:%@",str);
                ccell.isDEL=YES;
            }
        }
        
        //设置图片
        TweetImage *curImage = [_curTweet.tweetImages objectAtIndex:indexPath.row];
        urlStr = [_curTweet.selectedAssetURLs objectAtIndex:indexPath.row];
        //图片传递到自定义cell
        ccell.curTweetImg = curImage;
        
    }else{
        ccell.curTweetImg = nil;
    }
    

    ccell.deleteTweetImageBlock = ^(TweetImage *toDelete){
        
        if (weakSelf.deleteTweetImageBlock) {
            weakSelf.deleteTweetImageBlock(toDelete);
        }
        
        if(weakSelf.deleteTweetImageBlockUrl){
            weakSelf.deleteTweetImageBlockUrl(toDelete,urlStr);
        }
    };
    
    [_imageViewsDict setObject:ccell.imgView forKey:indexPath];
    return ccell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return [TweetSendImageCCell ccellSize];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsZero;
}
-(CGFloat )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;

}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _curTweet.tweetImages.count) {
        if (_addPicturesBlock) {
            _addPicturesBlock();
        }
    }else{
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:_curTweet.tweetImages.count];
        for (int i = 0; i < _curTweet.tweetImages.count; i++) {
            TweetImage *imageItem = [_curTweet.tweetImages objectAtIndex:i];
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.srcImageView = [_imageViewsDict objectForKey:indexPath]; // 来源于哪个UIImageView
            photo.image = imageItem.image; // 图片路径
            [photos addObject:photo];
        }
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = indexPath.row; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        browser.showSaveBtn = NO;
        [browser show];
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}



@end
